package controller

import (
	"backend/api"
	"backend/internal/biz"
	"backend/internal/service"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type UserController struct {
	users *service.UserService
	log   *zap.Logger
	jwt   *service.JwtService
}

func NewUserController(users *service.UserService, log *zap.Logger, jwt *service.JwtService) *UserController {
	return &UserController{users: users, log: log, jwt: jwt}
}

func (h *UserController) Login(c *gin.Context) {
	var form api.LoginParams
	if err := c.ShouldBindJSON(&form); err != nil {
		h.log.Error("Login bind json failed", zap.Error(err))
		api.FailByError(c, api.GetError(form, err))
		return
	}
	user, err := h.users.Login(c, form.Username, form.Password)
	if err != nil {
		h.log.Error("Login failed", zap.Error(err))
		api.FailByError(c, api.GetError(form, err))
		return
	}
	tokenData, _, err := h.jwt.CreateToken(biz.AppGuardName, user)
	if err != nil {
		h.log.Error("Generate token failed", zap.Error(err))
		api.FailByError(c, api.GetError(form, err))
		return
	}
	api.Success(c, tokenData)
}
